﻿using truongLibary;
using truongLibary.FACEDE;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using truongLibary.Truong;
using Functions;
using Facade;



namespace truongServer
{
    public partial class Form1 : Form
    {
        updateAdmin update;
        public Form1()
        {
            update = new updateAdmin();
            InitializeComponent();
            readXML();
        }



        public void readonlyFTP(bool readOnly = false)
        {
            txtFTP_Website.Properties.ReadOnly = readOnly;
            txtFTP_Address.Properties.ReadOnly = readOnly;
            txtFTP_Username.Properties.ReadOnly = readOnly;
            txtFTP_Password.Properties.ReadOnly = readOnly;
            txtFTP_Folder.Properties.ReadOnly = readOnly;
        }
        public Hashtable getPostFTP()
        {
            Hashtable myConnect = new Hashtable();
            myConnect["WEBSITE"] = txtFTP_Website.Text.Trim();
            myConnect["ADDRESS"] = txtFTP_Address.Text.Trim();
            myConnect["USERNAME"] = txtFTP_Username.Text.Trim();
            myConnect["PASSWORD"] = txtFTP_Password.Text.Trim();
            myConnect["FOLDER"] = txtFTP_Folder.Text.Trim();
            return myConnect;
        }
        public bool checkConnect(Uri uri, string user, string pass)
        {
            try
            {
                FtpWebRequest _lsDirFtp = (FtpWebRequest)FtpWebRequest.Create(uri);
                _lsDirFtp.Credentials = new NetworkCredential(user, pass);
                _lsDirFtp.Method = WebRequestMethods.Ftp.ListDirectory;
                FtpWebResponse response = (FtpWebResponse)_lsDirFtp.GetResponse();
                if (response.StatusCode == FtpStatusCode.OpeningData) { response.Close(); return true; }
                else { response.Close(); return false; }
            }
            catch (Exception ex) { Console.WriteLine(ex.Message); return false; }
        }
        private void createFolder(Uri uri, string user, string pass)
        {
            try
            {
                FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(uri);
                ftpRequest.Credentials = new NetworkCredential(user, pass);
                ftpRequest.UseBinary = true;
                ftpRequest.UsePassive = true;
                ftpRequest.KeepAlive = true;
                ftpRequest.Method = WebRequestMethods.Ftp.MakeDirectory;
                WebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                ftpResponse.Close();
                ftpRequest = null;
            }
            catch (Exception ex) { Console.WriteLine(ex.Message); }
        }
        bool isConnectFTP = false;
        private void btnConnectFTP_Click(object sender, EventArgs e)
        {

            if (btnConnectFTP.Tag.ToString() == "0")
            {
                if (!string.IsNullOrEmpty(txtFTP_Website.Text.Trim()))
                {
                    Hashtable ftpAccount = getPostFTP();
                    string url = "ftp://" + ftpAccount["ADDRESS"].ToString() + ":21";
                    if (checkConnect(new Uri(url), ftpAccount["USERNAME"].ToString(), ftpAccount["PASSWORD"].ToString()))
                    {
                        if (!string.IsNullOrEmpty(txtFTP_Folder.Text.Trim()))
                        {
                            url += "/" + ftpAccount["FOLDER"].ToString();
                            createFolder(new Uri(url), ftpAccount["USERNAME"].ToString(), ftpAccount["PASSWORD"].ToString());
                        }
                        btnConnectFTP.Text = "Ngắt kết nối";
                        btnConnectFTP.Tag = "1";
                        btnConnectFTP.Image = global::truongServer.Properties.Resources.x64FTPdisconnect;
                        readonlyFTP(true);
                        isConnectFTP = true;
                    }
                    else MessageBox.Show("Không thể kết nối tới địa chỉ FTP");
                }
                else MessageBox.Show("Vui lòng điền tên website.");
            }
            else
            {
                btnConnectFTP.Text = "Connect FTP";
                btnConnectFTP.Tag = "0";
                btnConnectFTP.Image = global::truongServer.Properties.Resources.x64FTPconnect;
                readonlyFTP();
                isConnectFTP = false;
            }
        }

        public Hashtable getPostDB()
        {
            Hashtable myConnect = new Hashtable();
            myConnect["ADDRESS"] = txtDB_Address.Text.Trim();
            myConnect["NAME"] = txtDB_Name.Text.Trim();
            myConnect["USERNAME"] = txtDB_Username.Text.Trim();
            myConnect["PASSWORD"] = txtDB_Password.Text.Trim();
            return myConnect;
        }
        public void readonlyCSDL(bool readOnly = false)
        {
            txtDB_Address.Properties.ReadOnly = readOnly;
            txtDB_Name.Properties.ReadOnly = readOnly;
            txtDB_Password.Properties.ReadOnly = readOnly;
        }
        bool isConnectDB = false;
        private void btnConnect_Click(object sender, EventArgs e)
        {
            if (btnConnect.Tag.ToString() == "0")
            {
                string cur = AppDomain.CurrentDomain.BaseDirectory;
                Database.setConnect(@"server=.\SQLExpress;AttachDBFilename=" + cur + @"Database\EXAMDB.MDF;Integrated security=True;User Instance=true");
                Database.Open();

                //if (truongLibary.sqlResult.connectDB(getPostDB()))
                //{
                btnConnect.Text = "Ngắt kết nối";
                btnConnect.Tag = "1";
                btnConnect.Image = global::truongServer.Properties.Resources.x48Disconnect;
                readonlyCSDL(true);
                isConnectDB = true;
                //}
                //else MessageBox.Show("Không thể kết nối tới cơ sở dữ liệu.");
            }
            else
            {
                btnConnect.Text = "Connect CSDL";
                btnConnect.Tag = "0";
                btnConnect.Image = global::truongServer.Properties.Resources.x48Connection;
                readonlyCSDL();
                isConnectDB = false;
                Database.Close();
            }
        }
        public string GetPublicIP()
        {
            String direction = "";
            try
            {
                WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
                using (WebResponse response = request.GetResponse())
                {
                    using (StreamReader stream = new StreamReader(response.GetResponseStream()))
                    {
                        direction = stream.ReadToEnd();
                    }
                }

                //Search for the ip in the html
                int first = direction.IndexOf("Address: ") + 9;
                int last = direction.LastIndexOf("</body>");
                direction = direction.Substring(first, last - first);
            }
            catch (Exception ex)
            {
                IPHostEntry host;
                host = Dns.GetHostEntry(Dns.GetHostName());
                foreach (IPAddress ip in host.AddressList)
                {
                    if (ip.AddressFamily == AddressFamily.InterNetwork)
                    {
                        direction = ip.ToString();
                    }
                }
            }
            return direction;
        }
        public string LocalIPAddress()
        {
            IPHostEntry host;
            string localIP = "";
            host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    localIP = ip.ToString();
                }
            }
            return localIP;
        }
        TcpChannel channel;
        private void btnConnectServer_Click(object sender, EventArgs e)
        {
            if (!isConnectDB) btnConnect_Click(null, null);
            if (isConnectDB)
            {
                if (!isConnectFTP) btnConnectFTP_Click(null, null);
                if (isConnectFTP)
                {
                    if (btnConnectServer.Tag.ToString() == "0")
                    {
                        Hashtable myPort = new Hashtable();
                        myPort["PORT"] = txtPort.Text.Trim();
                        channel = new TcpChannel(Int32.Parse(txtPort.Text.Trim()));
                        ChannelServices.RegisterChannel(channel, false);
                        //RemotingConfiguration.RegisterWellKnownServiceType(typeof(totalFac), "totalFac", WellKnownObjectMode.Singleton);
                        //RemotingConfiguration.RegisterWellKnownServiceType(typeof(adminFace), "adminFac", WellKnownObjectMode.Singleton);
                        //RemotingConfiguration.RegisterWellKnownServiceType(typeof(giangvienFace), "giangvienFac", WellKnownObjectMode.Singleton);
                        //RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemotingObject), "RemotingObject", WellKnownObjectMode.Singleton);
                        RemotingConfiguration.RegisterWellKnownServiceType(typeof(SuperFacade), "SuperFacade", WellKnownObjectMode.Singleton);
                        txtLocalhost.Text = "tcp://localhost" + ":" + txtPort.Text + "/";
                        txtLan.Text = "tcp://" + LocalIPAddress() + ":" + txtPort.Text + "/";
                        txtInternet.Text = "tcp://" + GetPublicIP() + ":" + txtPort.Text + "/";
                        txtPort.Properties.ReadOnly = true;
                        groupCSDL.Enabled = false;
                        groupFTP.Enabled = false;
                        btnConnectServer.Text = "Stop Server";
                        btnConnectServer.Tag = "1";
                        btnConnectServer.Image = global::truongServer.Properties.Resources.x64Disconnect;
                        writeXML(getPostDB(), getPostFTP(), myPort);
                        totalFac.getFTPInfor(getPostFTP());
                        n = 0;
                        timeCheckUser.Start();
                        getconnect();


                    }
                    else
                    {
                        DialogResult rs = MessageBox.Show("Bạn có muốn ngừng Server?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                        if (rs == System.Windows.Forms.DialogResult.Yes) Application.Exit();
                    }
                }
            }

        }
        int n = 0;
        private void timeCheckUser_Tick(object sender, EventArgs e)
        {
            int temp = RemotingObject.getList().Count;
            if (temp != n)
            {
                n = temp;
                lvlUser.Items.Clear();
                foreach (var str in RemotingObject.getList())
                {
                    ListViewItem item = new ListViewItem(str.Value);
                    lvlUser.Items.Add(item);
                }
            }
            if (RemotingObject.listDele.Count != 0)
            {
                int checkOut = 0;
                foreach (var temp2 in RemotingObject.getList())
                {
                    if (RemotingObject.listDele.ContainsKey(temp2.Key)) checkOut = 1;
                }
                if (checkOut == 0) RemotingObject.listDele.Clear();
            }
        }


        public void readXML()
        {
            try
            {
                if (File.Exists("config.xml"))
                {
                    XmlReader reader = XmlReader.Create("config.xml");
                    while (reader.Read())
                    {
                        if (reader.NodeType == XmlNodeType.Element)
                        {
                            if (reader.Name == "DATABASE")
                            {
                                txtDB_Address.Text = reader.GetAttribute(0);
                                txtDB_Username.Text = reader.GetAttribute(1);
                                txtDB_Password.Text = reader.GetAttribute(2);
                            }
                            if (reader.Name == "FTP")
                            {
                                txtFTP_Website.Text = reader.GetAttribute(0);
                                txtFTP_Address.Text = reader.GetAttribute(1);
                                txtFTP_Username.Text = reader.GetAttribute(2);
                                txtFTP_Password.Text = reader.GetAttribute(3);
                                txtFTP_Folder.Text = reader.GetAttribute(4);
                            }
                            if (reader.Name == "SERVER") txtPort.Text = reader.GetAttribute(0);
                        }
                    }
                    reader.Close();
                }
            }
            catch (Exception) { }
        }

        public static void writeXML(Hashtable hashDB, Hashtable hashFTP, Hashtable hashPort)
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            XmlWriter writer = XmlWriter.Create("config.xml", settings);
            writer.WriteStartDocument();
            writer.WriteStartElement("CONFIG");
            writer.WriteStartElement("DATABASE");
            writer.WriteAttributeString("ADDRESS", hashDB["ADDRESS"].ToString());
            writer.WriteAttributeString("USERNAME", hashDB["USERNAME"].ToString());
            writer.WriteAttributeString("PASSWORD", hashDB["PASSWORD"].ToString());
            writer.WriteEndElement();
            writer.WriteWhitespace("\n");
            writer.WriteStartElement("FTP");
            writer.WriteAttributeString("WEBSITE", hashFTP["WEBSITE"].ToString());
            writer.WriteAttributeString("ADDRESS", hashFTP["ADDRESS"].ToString());
            writer.WriteAttributeString("USERNAME", hashFTP["USERNAME"].ToString());
            writer.WriteAttributeString("PASSWORD", hashFTP["PASSWORD"].ToString());
            writer.WriteAttributeString("FOLDER", hashFTP["FOLDER"].ToString());
            writer.WriteEndElement();
            writer.WriteWhitespace("\n");
            writer.WriteStartElement("SERVER");
            writer.WriteAttributeString("PORT", hashPort["PORT"].ToString());
            writer.WriteEndElement();
            writer.WriteWhitespace("\n");
            writer.WriteEndElement();
            writer.WriteEndDocument();
            writer.Flush();
            writer.Close();
        }
        int status = 0;
        public void getconnect()
        {
            status = 0;
            timer1.Stop();
            toolStripProgressBar1.Style = ProgressBarStyle.Marquee;
            lableStatus.Text = "Đang kết nối với máy chủ";
            bgrConnect.RunWorkerAsync();
        }
        private void bgrConnect_DoWork(object sender, DoWorkEventArgs e)
        {
            update.getURL();
            status = update.getConnet();
        }
        adminLibaryServer.FACEDE.adminFac adFace;
        private void bgrConnect_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (status == 1)
            {
                toolStripProgressBar1.Style = ProgressBarStyle.Blocks;
                lableStatus.Text = "Kết nối thất bại.";
                DialogResult rs = MessageBox.Show("Kết nối server thất bại, bạn có muốn cấu hình lại server", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (rs == System.Windows.Forms.DialogResult.Yes)
                {
                    Dictionary<string, string> dics = update.readXML();
                    string url = ""; string port = "";
                    foreach (var dic in dics)
                    {
                        url = dic.Value;
                        port = dic.Key;
                        break;
                    }
                    frmConnectToServerCapCao connect = new frmConnectToServerCapCao(url, port);
                    if (connect.ShowDialog() == System.Windows.Forms.DialogResult.OK) { getconnect(); }
                }
                else
                {
                    toolStripProgressBar1.Style = ProgressBarStyle.Blocks;
                    lableStatus.Text = "";
                    timer1.Start();
                }

            }
            else if (status == 0)
            {
                adFace = getConnectToServerCapCao.AdminFac;
                truong = adFace.viewAllTruong();
                toolStripProgressBar1.Style = ProgressBarStyle.Blocks;
                lableStatus.Text = "";
                dangnhapAdminServer dangnhap = new dangnhapAdminServer(adFace, update);
                DialogResult dr = dangnhap.ShowDialog();
                Console.WriteLine(dr.ToString());
                if (dr == DialogResult.OK) { check.Start(); totalFac.getIDtruong(update.idTruong.ToString()); }
                else { totalFac.getIDtruong(null); }
            }
        }
        List<Entities.tblTruongHoc> truong;
        private void check_Tick(object sender, EventArgs e)
        {
            check.Stop();
            if (!backgroundWorker2.IsBusy)
            {
                //toolStripProgressBar1.Style = ProgressBarStyle.Marquee;
                //lableStatus.Text = "Đồng bộ hóa dữ liệu.";
                backgroundWorker2.RunWorkerAsync();
            }


        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            status = 0;
            timer1.Stop();
            backgroundWorker1.RunWorkerAsync();


        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            update.getURL();
            status = update.getConnet();
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (status == 1)
            {
                Console.WriteLine("KO");
                timer1.Start();
            }
            else check.Start();
        }

        private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                List<Entities.tblAdmin> admins = adFace.viewAllAdmin();
                string query = "SELECT * FROM tblAdmin";
                DataTable dt = sqlResult.returnDB(query);
                if (dt != null)
                {
                    ArrayList tmp = new ArrayList();
                    foreach (Entities.tblAdmin admin in admins)
                    {
                        if (admin.IdTruong == update.idTruong) tmp.Add(admin);
                    }
                    Console.WriteLine(tmp.Count + " - " + dt.Rows.Count);
                    if (tmp.Count != dt.Rows.Count)
                    {
                        foreach (Entities.tblAdmin admin in tmp)
                        {
                            Hashtable myHash = new Hashtable();
                            myHash["parentID"] = admin.ParentID;
                            myHash["email"] = admin.Email;
                            myHash["password"] = sqlResult.Encrypt(admin.Password);
                            myHash["fullName"] = admin.FullName;
                            myHash["phoneNumber"] = admin.PhoneNumber;
                            myHash["enable"] = admin.Enable;
                            sqlResult.insertMedia(myHash, "tblAdmin", "avatar", (object)admin.Avatar);
                        }
                    }
                }
            }
            catch (Exception) { Console.WriteLine("ko thay du lieu"); }
        }

        private void backgroundWorker2_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //toolStripProgressBar1.Style = ProgressBarStyle.Blocks;
            //lableStatus.Text = "";
            check.Start();
        }
    }
}
